<?php


namespace app\controller\api;


use app\BaseController;
use app\model\cart\VerifyCartModel;
use app\model\coach\CoachRatioModel;
use app\model\partner\EscortMenuModel;
use app\model\partner\EscortMenuOrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\UserPartnerModel;
use app\model\school\SchoolOrderModel;
use app\model\user\UserCouponModel;
use app\service\order\PartnerOrderService;
use app\service\user\UserPartnerService;
use app\service\user\UserService;
use app\service\utils\WeiXinPayService;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class NotifyController extends BaseController
{
    /**
     * 验车支付回调
     * @return \Symfony\Component\HttpFoundation\Response|\think\response\Json
     */
    public function verifyCartNotify()
    {
        try {
            $weiXinPayService = new WeiXinPayService();
            $app = $weiXinPayService->getApp();
            $response = $app->handlePaidNotify(function ($message, $fail) {
                Log::info('验车订单支付回调：' . json_encode($message));
                Db::transaction(function () use ($message, $fail) {
                    $orderInfo = EscortMenuOrderModel::where('order_sn', $message['out_trade_no'])->find();
                    if (!$orderInfo || $orderInfo->pay_status != 1) {
                        return true;
                    }
                    if ($orderInfo['pay_status'] == 2) {
                        return true;
                    }
                    if ($message['return_code'] !== 'SUCCESS') {
                        return $fail('通信失败，请稍后再通知我');
                    }
                    // 用户是否支付成功
                    if ($message['result_code'] === 'FAIL') {
                        $orderInfo->pay_status = -1;
                        $orderInfo->fail_reason = $message['err_code_des'];
                        $orderInfo->save();
                        return true;
                    }
                    $orderInfo->pay_status = 2;
                    $orderInfo->pay_time = time();
                    $orderInfo->save();

                    // 添加预约单
                    $escortMenuReserveOrderInfo = EscortMenuReserveOrderModel::withTrashed()->where('order_sn', $message['out_trade_no'])->find();
                    $escortMenuReserveOrderInfo->restore();

                    // 套餐销售数量
                    $menuInfo = EscortMenuModel::find($orderInfo['menu_id']);
                    $menuInfo->sale_num = Db::raw('sale_num+' . $orderInfo['num']);
                    $menuInfo->save();

                    // 销毁用户优惠券
                    if ($orderInfo['user_coupon_id']) {
                        $userCoupon = UserCouponModel::find($orderInfo['user_coupon_id']);
                        $userCoupon->is_used = 1;
                        $userCoupon->use_time = time();
                        $userCoupon->save();
                    }

                    // 新订单通知
                    Queue::push('WeiXinTemplateMsgJob', ['msg_type' => 'new_order', 'id' => $escortMenuReserveOrderInfo->id]);
                    return true;
                });
            });
            return $response->send();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 陪驾支付回调
     * @return \Symfony\Component\HttpFoundation\Response|\think\response\Json
     */
    public function partnerDriveNotify()
    {
        try {
            $weiXinPayService = new WeiXinPayService();
            $app = $weiXinPayService->getApp();
            $response = $app->handlePaidNotify(function ($message, $fail) {
                Log::info('陪驾订单支付回调：' . json_encode($message));
                Db::transaction(function () use ($message, $fail) {
                    $orderInfo = EscortMenuOrderModel::where('order_sn', $message['out_trade_no'])->find();
                    if (!$orderInfo || $orderInfo->pay_status != 1) {
                        return true;
                    }
                    if ($orderInfo['pay_status'] == 2) {
                        return true;
                    }
                    if ($message['return_code'] !== 'SUCCESS') {
                        return $fail('通信失败，请稍后再通知我');
                    }
                    // 用户是否支付成功
                    if ($message['result_code'] === 'FAIL') {
                        $orderInfo->pay_status = -1;
                        $orderInfo->fail_reason = $message['err_code_des'];
                        $orderInfo->save();
                        return true;
                    }
                    $orderInfo->pay_status = 2;
                    $orderInfo->pay_time = time();
                    $orderInfo->save();

                    // 套餐销售数量
                    $menuInfo = EscortMenuModel::find($orderInfo['menu_id']);
                    $menuInfo->sale_num = Db::raw('sale_num+' . $orderInfo['num']);
                    $menuInfo->save();

                    // 销毁用户优惠券
                    if ($orderInfo['user_coupon_id']) {
                        $userCoupon = UserCouponModel::find($orderInfo['user_coupon_id']);
                        $userCoupon->is_used = 1;
                        $userCoupon->use_time = time();
                        $userCoupon->save();
                    }
                    // 用户购买正式套餐
                    PartnerOrderService::setPartnerRatio($orderInfo['user_id']);
                    return true;
                });
            });
            return $response->send();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 学车支付回调
     * @return \Symfony\Component\HttpFoundation\Response|\think\response\Json
     */
    public function studyCardNotify()
    {
        try {
            $weiXinPayService = new WeiXinPayService();
            $app = $weiXinPayService->getApp();
            $response = $app->handlePaidNotify(function ($message, $fail) {
                Log::info('学车订单支付回调：' . json_encode($message));
                $orderInfo = SchoolOrderModel::where('order_sn', $message['out_trade_no'])->find();
                if (!$orderInfo || $orderInfo->status != 1) {
                    return true;
                }
                if ($message['return_code'] !== 'SUCCESS') {
                    return $fail('通信失败，请稍后再通知我');
                }
                // 用户是否支付成功
                if ($message['result_code'] === 'FAIL') {
                    $orderInfo->status = -1;
                    $orderInfo->reason = $message['err_code_des'];
                    $orderInfo->save();
                    return true;
                }
                $orderInfo->pay_type = 1;
                $orderInfo->status = 2;
                $orderInfo->save();

                // 销毁用户优惠券
                if ($orderInfo['user_coupon_id']) {
                    $userCoupon = UserCouponModel::find($orderInfo['user_coupon_id']);
                    $userCoupon->is_used = 1;
                    $userCoupon->use_time = time();
                    $userCoupon->save();
                }
                return true;
            });
            return $response->send();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}